#ifndef JSONHELPER_H
#define JSONHELPER_H

#include <QObject>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QDebug>

class JsonHelper
{
public:
    JsonHelper();

    enum StateCode{
        StateOk,
        StateErr
    };

    //读文件，返回键值对列表
    static int ReadJsonFromFile(const QString &file_name, QJsonObject &list);

    //根据键名修改对应的值
    template <typename T> static int ModifyJson(const QString &file_name, const QString &title, T &content){
        QJsonObject obj;
        ReadJsonFromFile(file_name, obj);
        obj[title] = content;

        QFile file(file_name);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            qDebug() << "file open error";
            return StateErr;
        }
        QJsonDocument json_update(obj);
        QByteArray updated_data = json_update.toJson(QJsonDocument::Indented);
        file.write(updated_data);
        file.close();
        return StateOk;
    }
};

#endif // JSONHELPER_H
